﻿#include "PlayAndRecordRTSPStreamWindow.h"
#include <QMessageBox>
#include <QString>
#include <QFileDialog>
#include <thread>

PlayAndRecordRTSPStreamWindow::PlayAndRecordRTSPStreamWindow(QWidget* parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	this->setWindowTitle("播放并录制RTSP流");
	setAttribute(Qt::WA_DeleteOnClose, true);  // 关闭时自动销毁窗口
	//timer = new QTimer();
	//connect(timer, &QTimer::timeout, this, &PlayAndRecordRTSPStreamWindow::OnTimeout);
	//timer->setInterval(100);//设置定时间隔
	//timer->start();//启动定时器

}

void PlayAndRecordRTSPStreamWindow::OnTimeout()
{
	/*qDebug() << "展示画面";
	auto frame = decoderTask->GetFrame();
	if (frame && view)
	{
		view->DrawFrame(frame);
	}*/
}

void PlayAndRecordRTSPStreamWindow::SelectInputFilePath()
{
	QString filter = "所有文件(*.*)"; //文件过滤器
	QString filePath = QFileDialog::getOpenFileName(this, "请选择输入文件", "", filter);
	this->inputFilePath = filePath;
	this->ui.inputPathEdit->setText(this->inputFilePath);
}

void PlayAndRecordRTSPStreamWindow::SelectOutputFilePath()
{
	QString filter = "所有文件(*.*)"; //文件过滤器
	QString filePath = QFileDialog::getSaveFileName(this, "选择文件输出目录", "", filter);
	this->outputFilePath = filePath;
	this->ui.outputPathEdit->setText(this->outputFilePath);
}

void PlayAndRecordRTSPStreamWindow::OnPaternChanged(int pos)
{
	switch (pos)
	{
	case 0://播放
		pattern_type = 0;
		break;
	case 1://录制
		pattern_type = 1;
		break;
	case 2://播放并录制
		pattern_type = 2;
		break;
	}
}

//开始播放rtsp流并播放
void PlayAndRecordRTSPStreamWindow::StartPlay()
{
	QString filePath = this->ui.inputPathEdit->text();
	if (filePath.isEmpty())
	{
		QMessageBox::information(this, "温馨提示", "请输入流地址");
		return;
	}

	qDebug() << "开始播放并录制.......";

	//解封装任务
	demuxerTask = new YDemuxerTask();
	for (;;)//循环打开，如果没有网络，可循环连接
	{
		if (demuxerTask->Open(filePath.toStdString().c_str()))
		{
			break;
		}
		MSleep(100);
		continue;
	}
	qDebug() << "连接成功";
	auto vpara = demuxerTask->CopyVideoPara();
	AVCodecParameters* video_para = nullptr;
	AVCodecParameters* audio_para = nullptr;
	AVRational* video_time_base = nullptr;
	AVRational* audio_time_base = nullptr;
	if (vpara)
	{
		video_para = vpara->para;
		video_time_base = vpara->time_base;
	}

	auto apara = demuxerTask->CopyAudioPara();
	if (apara)
	{
		audio_para = apara->para;
		audio_time_base = apara->time_base;
	}

	isRunning = true;//即是线程的标志位，也是销毁方法的标志位
	switch (pattern_type)
	{
	case 0:
	{
		//解码任务
		decoderTask = new YDecoderTask();
		if (!decoderTask->Open(video_para)) {
			qDebug() << "打开解码器失败";
			return;
		}
		demuxerTask->setNext(decoderTask);
		demuxerTask->Start();
		decoderTask->Start();
		view = IVideoRenderView::Create();
		view->Init(demuxerTask->getWidth(), demuxerTask->getHeight(), IVideoRenderView::YUV420P, (void*)ui.labelVideo->winId());
		renderThread = std::thread(&PlayAndRecordRTSPStreamWindow::OnRenderView, this);
	}
	break;
	case 1:
	{
		//封装任务
		muxerTask = new YMuxerTask();
		if (!muxerTask->Open(this->outputFilePath.toStdString().c_str(), video_para, video_time_base, audio_para, audio_time_base))
		{
			LOGERROR("YMuxerTask.Open failed!");
			return;
		}
		qDebug() << "开始解封装..............";
		demuxerTask->setNext(muxerTask);
		//开始解封装线程
		demuxerTask->Start();
		//封装线程
		muxerTask->Start();
	}
	break;
	case 2:
	{

	}
	break;
	}

	

	//以下方式搞一个线程就会出问题
	//std::thread t([this]() {
		/*for (;;)
		{
			qDebug() << "开始循环";
			auto frame = decoderTask->GetFrame();
			if (frame)
			{
				if (!view->DrawFrame(frame))break;
			}
			else {
				std::this_thread::sleep_for(std::chrono::milliseconds(10));
				continue;
			}
			qDebug() << "开始绘制";

		}
		view->Close();*/
		/*});*/
	//t.detach();

	



}

void PlayAndRecordRTSPStreamWindow::OnRenderView()
{
	while (isRunning)
	{
		qDebug() << "开始循环";
		auto frame = decoderTask->GetFrame();
		if (frame)
		{
			if (!view->DrawFrame(frame))break;
			std::this_thread::sleep_for(std::chrono::milliseconds(1000/25));
		}
		else {
			std::this_thread::sleep_for(std::chrono::milliseconds(10));
			continue;
		}
		qDebug() << "开始绘制";

	}
	view->Close();
}

void PlayAndRecordRTSPStreamWindow::Release()
{
	if (isRunning)
	{
		isRunning = false;
		if (renderThread.joinable())
		{
			renderThread.join();
		}
		if (demuxerTask)
		{
			demuxerTask->Stop();
			delete demuxerTask;
			demuxerTask = nullptr;
		}

		if (muxerTask)
		{
			muxerTask->Stop();
			delete muxerTask;
			muxerTask = nullptr;
		}

		if (demuxerTask)
		{
			demuxerTask->Stop();
			delete demuxerTask;
			demuxerTask = nullptr;
		}

		if (view)
		{
			view->Close();
			delete view;
			view = nullptr;
		}
	}
	

}
void PlayAndRecordRTSPStreamWindow::closeEvent(QCloseEvent* event) {
	event->accept();  // 接受关闭事件（允许关闭）
	Release();
	qDebug() << "窗口已关闭";

}

PlayAndRecordRTSPStreamWindow::~PlayAndRecordRTSPStreamWindow()
{
	Release();
}
